package com.yanchangapp.ui.activity.purchase;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.Spanned;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.luck.picture.lib.decoration.RecycleViewDivider;
import com.luck.picture.lib.tools.ScreenUtils;
import com.yanchangapp.R;
import com.yanchangapp.adapter.PsCntCreateListAdapter;
import com.yanchangapp.adapter.WareHouseAdapter;
import com.yanchangapp.commom.LoadingType;
import com.yanchangapp.model.bean.ProductBean;
import com.yanchangapp.model.bean.ProductExtractBean;
import com.yanchangapp.model.bean.WareHouseBean;
import com.yanchangapp.model.cache.UserCache;
import com.yanchangapp.ui.presenter.POrderCtCntAtPresenter;
import com.yanchangapp.ui.view.POrderCtCntAtView;
import com.yanchangapp.widget.BottomDialog;
import com.yanchangapp.widget.SpannableMoney;
import com.zxl.baselib.baseapp.AppManager;
import com.zxl.baselib.ui.base.BaseActivity;
import com.zxl.baselib.util.formatter.BigDecimalUtils;
import com.zxl.baselib.util.time.TimeUtil;
import com.zxl.baselib.util.ui.ResHelper;
import com.zxl.baselib.util.ui.UIUtils;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
/**
 *
 * 从合同进入  ==> 填写采购明细页面
 */
public class POrderCtCntActivity extends BaseActivity<POrderCtCntAtView, POrderCtCntAtPresenter> implements POrderCtCntAtView, PsCntCreateListAdapter.ITotalAmountChanged {
    @BindView(R.id.ivToolbarNavigation)
    ImageView ivToolbarNavigation;
    @BindView(R.id.vToolbarDivision)
    View vToolbarDivision;
    @BindView(R.id.tvToolbarTitle)
    TextView tvToolbarTitle;
    @BindView(R.id.tv_publish_now)
    TextView tvPublishNow;
    @BindView(R.id.btnCreate)
    Button btnCreate;
    @BindView(R.id.tvProductSum)
    TextView tvProductSum;
    @BindView(R.id.linearBottom)
    RelativeLayout linearBottom;
    @BindView(R.id.tvTime)
    TextView tvTime;
    @BindView(R.id.tvDepartment)
    TextView tvDepartment;
    @BindView(R.id.tvManName)
    TextView tvManName;
    @BindView(R.id.tvSupplierName)
    TextView tvSupplierName;
    @BindView(R.id.tvInvoiceNo)
    TextView tvInvoiceNo;
    @BindView(R.id.tvChooseProduct)
    TextView tvChooseProduct;
    @BindView(R.id.tvProductEmpty)
    TextView tvProductEmpty;
    @BindView(R.id.rlWareHouse)
    RelativeLayout mRlWareHouse;
    @BindView(R.id.tvWareHouse)
    TextView mTvWareHouse;
    @BindView(R.id.rvProductList)
    RecyclerView mRvProductList;

    private static final String CONTRACT_ID = "contractId";
    private static final String SUPPLIER_ID = "supplierId";
    private static final String SUPPLIER_NAME = "supplierName";
    private static final String INVOICE_NO = "invoiceNo";
    private String mContractId,mSupplierId,mSupplierName,mInvoiceNo;

    // 仓库地址 相关的信息
    private BottomDialog mBottomCangKuArea;
    // 仓库地址适配器
    private WareHouseAdapter mWareHouseAdapter;
    // 仓库地址数据层
    private List<WareHouseBean> mWareHouseBeans = new ArrayList<>();
    // 仓库地址RecyclerView
    private RecyclerView mWareHouseRv;
    // 加载中view
    private LinearLayout mWareLlLoading,mWareLlEmpty;
    private RelativeLayout mWareRlError;
    // 是否数据已经加载
    private boolean mIsWareHouseLoading = false;
    // 之前选中的index
    private int mPreIndex = -1;
    // 现在选中的index 判断是否选中了对应的index....
    private int mNowIndex = -1;


    private static final String TAG = "填写采购明细";
    private PsCntCreateListAdapter mPsCntCreateListAdapter;
    private List<ProductExtractBean> mExtractBeanList = new ArrayList<>();
    private static final int REQUEST_PRODUCT_CODE = 0x0099;

    private double totalMoney = 0;
    @Override
    protected void init() {
        if (getIntent() == null){
            finish();
        }else {
            mContractId = getIntent().getStringExtra(CONTRACT_ID);
            mSupplierId = getIntent().getStringExtra(SUPPLIER_ID);
            mSupplierName = getIntent().getStringExtra(SUPPLIER_NAME);
            mInvoiceNo = getIntent().getStringExtra(INVOICE_NO);
        }
    }

    @Override
    protected void onDestroy() {
        if (mBottomCangKuArea != null){
            mBottomCangKuArea.dismiss();
        }
        super.onDestroy();
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_porder_ct_cnt;
    }

    @Override
    protected POrderCtCntAtPresenter createPresenter() {
        return new POrderCtCntAtPresenter(this);
    }


    public static void show(Activity activity,String contractId,String supplierId,String supplierName,String invoiceNo){
        Intent intent = new Intent(activity,POrderCtCntActivity.class);
        intent.putExtra(CONTRACT_ID,contractId);
        intent.putExtra(SUPPLIER_ID,supplierId);
        intent.putExtra(SUPPLIER_NAME,supplierName);
        intent.putExtra(INVOICE_NO,invoiceNo);
        activity.startActivity(intent);
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        tvPublishNow.setVisibility(View.VISIBLE);
        tvPublishNow.setText("取消");
        tvToolbarTitle.setText("填写采购明细");
        setSumText();
        setViewFromBefore();
        initAdapter();
    }

    private void initAdapter() {
        LinearLayoutManager manager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        manager.setSmoothScrollbarEnabled(true);
        manager.setAutoMeasureEnabled(true);
        mRvProductList.setHasFixedSize(true);
        mRvProductList.setNestedScrollingEnabled(false);
        mRvProductList.addItemDecoration(new RecycleViewDivider(
                this, LinearLayoutManager.HORIZONTAL, ScreenUtils.dip2px(this, 0.5f), ContextCompat.getColor(this, R.color.borderColorBase)));
        mRvProductList.setLayoutManager(manager);
        mPsCntCreateListAdapter = new PsCntCreateListAdapter(R.layout.item_ps_create_list_cnt,mExtractBeanList);
        mPsCntCreateListAdapter.setITotalAmountChanged(this);
        // 设置adapter...
        mRvProductList.setAdapter(mPsCntCreateListAdapter);
    }

    /**
     * 设置从上一个页面传递的数据
     */
    private void setViewFromBefore() {
        tvInvoiceNo.setText(mInvoiceNo);
        tvTime.setText(TimeUtil.getTodayDayTime());
        tvDepartment.setText(UserCache.getDepartmentName());
        tvManName.setText(UserCache.getName());
        tvSupplierName.setText(mSupplierName);
    }

    /**
     * 加载仓库地址的sheet
     */
    private void showWareHouseSheet(){
        if (mBottomCangKuArea == null){
            mBottomCangKuArea = new BottomDialog(this,0,true);
            View view = LayoutInflater.from(this).inflate(R.layout.bottom_cangku_area, null, false);
            mBottomCangKuArea.setContentView(view);
            // 设置背景为透明色 那么白色的就能呈现出来了
            mBottomCangKuArea.getDelegate().findViewById(android.support.design.R.id.design_bottom_sheet)
                    .setBackgroundColor(getResources().getColor(android.R.color.transparent));
            mWareHouseRv = view.findViewById(R.id.rvWareHouse);
            mWareLlEmpty = view.findViewById(R.id.llEmpty);
            mWareLlLoading = view.findViewById(R.id.llLoading);
            mWareRlError = view.findViewById(R.id.rlErrorNetwork);
            TextView mTvWareRefresh = view.findViewById(R.id.btnNextRefresh);
            TextView tvToolbarTitle = view.findViewById(R.id.tvToolbarTitle);
            tvToolbarTitle.setText("选择仓库地址");
            view.findViewById(R.id.closeBottom).setOnClickListener(v -> mBottomCangKuArea.hide());
            mWareHouseRv.addItemDecoration(new RecycleViewDivider(
                    this, LinearLayoutManager.HORIZONTAL, ScreenUtils.dip2px(this,0.5f), ContextCompat.getColor(this, R.color.borderColorBase)));
            mWareHouseRv.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
            mWareHouseAdapter = new WareHouseAdapter(R.layout.item_checkbox_text,mWareHouseBeans);
            mWareHouseAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                    if (mNowIndex == i){
                        // 如果相等直接关闭
                        mBottomCangKuArea.hide();
                        return;
                    }

                    mPreIndex = mNowIndex;
                    if (mPreIndex != -1){
                        mWareHouseBeans.get(mPreIndex).setChecked(false);
                        mWareHouseAdapter.notifyItemChanged(mPreIndex);
                    }
                    mNowIndex = i;
                    mWareHouseBeans.get(mNowIndex).setChecked(true);
                    // 设置变化
                    mWareHouseAdapter.notifyItemChanged(mNowIndex);
                    // 设置仓库地址...
                    mTvWareHouse.setText(mWareHouseBeans.get(mNowIndex).getName());
                    mBottomCangKuArea.hide();
                }
            });
            mTvWareRefresh.setOnClickListener(v -> loadWareHouseData());
            // 设置Adapter
            mWareHouseRv.setAdapter(mWareHouseAdapter);
        }
        // 加载数据
        loadWareHouseData();
        // 进行数据加载
        if (!isFinishing()){
            mBottomCangKuArea.show();
        }
    }


    private void setWareSheetState(LoadingType loadingType){
        switch (loadingType){
            case SUCCESS:
                if (mWareHouseRv.getVisibility() == View.GONE){
                    mWareHouseRv.setVisibility(View.VISIBLE);
                }
                if (mWareRlError.getVisibility() == View.VISIBLE){
                    mWareRlError.setVisibility(View.GONE);
                }
                if (mWareLlLoading.getVisibility() == View.VISIBLE){
                    mWareLlLoading.setVisibility(View.GONE);
                }
                if (mWareLlEmpty.getVisibility() == View.VISIBLE){
                    mWareLlEmpty.setVisibility(View.GONE);
                }
                break;
            case LOADING:
                if (mWareHouseRv.getVisibility() == View.VISIBLE){
                    mWareHouseRv.setVisibility(View.GONE);
                }
                if (mWareRlError.getVisibility() == View.VISIBLE){
                    mWareRlError.setVisibility(View.GONE);
                }
                if (mWareLlLoading.getVisibility() == View.GONE){
                    mWareLlLoading.setVisibility(View.VISIBLE);
                }
                if (mWareLlEmpty.getVisibility() == View.VISIBLE){
                    mWareLlEmpty.setVisibility(View.GONE);
                }
                break;
            case EMPTY:
                if (mWareHouseRv.getVisibility() == View.VISIBLE){
                    mWareHouseRv.setVisibility(View.GONE);
                }
                if (mWareRlError.getVisibility() == View.VISIBLE){
                    mWareRlError.setVisibility(View.GONE);
                }
                if (mWareLlLoading.getVisibility() == View.VISIBLE){
                    mWareLlLoading.setVisibility(View.GONE);
                }
                if (mWareLlEmpty.getVisibility() == View.GONE){
                    mWareLlEmpty.setVisibility(View.VISIBLE);
                }
                break;
            case ERROR:
                if (mWareHouseRv.getVisibility() == View.VISIBLE){
                    mWareHouseRv.setVisibility(View.GONE);
                }
                if (mWareRlError.getVisibility() == View.GONE){
                    mWareRlError.setVisibility(View.VISIBLE);
                }
                if (mWareLlLoading.getVisibility() == View.VISIBLE){
                    mWareLlLoading.setVisibility(View.GONE);
                }
                if (mWareLlEmpty.getVisibility() == View.VISIBLE){
                    mWareLlEmpty.setVisibility(View.GONE);
                }
                break;
        }
    }

    private void loadWareHouseData(){
        if (!mIsWareHouseLoading){
            setWareSheetState(LoadingType.LOADING);
            mPresenter.loadWareHouseData();
        }
    }


    @Override
    protected void initData() {

    }

    @Override
    protected void initListener() {
        ivToolbarNavigation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });


        tvPublishNow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AppManager.getAppManager().returnToActivity(POrderListActivity.class);
            }
        });

        tvChooseProduct.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ProductExtractActivity.show(POrderCtCntActivity.this,mContractId,mExtractBeanList);
            }
        });

        mRlWareHouse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showWareHouseSheet();
            }
        });

        mPsCntCreateListAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.ivDelete){
                    mExtractBeanList.remove(position);
                    mPsCntCreateListAdapter.notifyItemRemoved(position);
                    mPsCntCreateListAdapter.notifyItemRangeChanged(position, mExtractBeanList.size() - position);
                    setSumText();
                    if (mExtractBeanList.size() == 0){
                        tvProductEmpty.setVisibility(View.VISIBLE);
                        mRvProductList.setVisibility(View.GONE);
                    }
                }
            }
        });

        /**
         * 生成订单点击事件....
         */
        btnCreate.setOnClickListener(v -> {
            // 如果检查失败,直接返回
            // 这里只检查仓库地址以及品种选择
            if (!isCheckOk()){
                return;
            }
            List<ProductBean> mProductLists = new ArrayList<>();
            for (int i=0;i<mExtractBeanList.size();i++){
                ProductExtractBean bean = mExtractBeanList.get(i);
                mProductLists.add(new ProductBean(
                        bean.getProductId(),bean.getSelectSize(),bean.getPrice(),
                        bean.getPrice() * bean.getSelectSize()));
            }
            mPresenter.actionCreateOrder(mContractId,mSupplierId,
                    mWareHouseBeans.get(mNowIndex).getId()
                    ,totalMoney,
                    mProductLists);
        });
    }


    private boolean isCheckOk(){
        if (mNowIndex == -1){
            UIUtils.showToast("请选择仓库地址");
            return  false;
        }

        if (mExtractBeanList.size() == 0){
            UIUtils.showToast("请进行品种选择");
            return  false;
        }
        return true;
    }

    @Override
    public void queryWareHouseSuccess(List<WareHouseBean> mWareBeanList) {
        mIsWareHouseLoading = true;
        if (mWareBeanList == null || mWareBeanList.size() == 0){
            // 数据为空的情况
            setWareSheetState(LoadingType.EMPTY);
        }else {
            setWareSheetState(LoadingType.SUCCESS);
            if (mWareHouseAdapter != null && mBottomCangKuArea.isShowing()){
                mWareHouseBeans.addAll(mWareBeanList);
                mWareHouseAdapter.notifyDataSetChanged();
                setSumText();
            }
        }
    }

    @Override
    public void queryWareHouseFailure(String err) {
        setWareSheetState(LoadingType.ERROR);
        mIsWareHouseLoading = false;
        UIUtils.showToast(err);
    }

    @Override
    public void createOrderSuccess(String orderID) {
        mRxManager.post(POrderListActivity.REFRESH_LIST,true);
        POrderEnsureActivity.show(POrderCtCntActivity.this,orderID);
    }

    @Override
    public void createOrderFailure(String err) {
        UIUtils.showToast(err);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK){
            switch (requestCode){
                case REQUEST_PRODUCT_CODE:
                    mExtractBeanList.clear();
                    mExtractBeanList.addAll((List<ProductExtractBean>)data.getExtras().getSerializable("data"));
                    mPsCntCreateListAdapter.notifyDataSetChanged();
                    if (tvProductEmpty.getVisibility() == View.VISIBLE){
                        tvProductEmpty.setVisibility(View.GONE);
                    }

                    if (mRvProductList.getVisibility() == View.GONE){
                        mRvProductList.setVisibility(View.VISIBLE);
                    }
                    setSumText();
                    break;
                default:
                    break;
            }
        }
    }


    private void setSumText(){
        String totalMoney = BigDecimalUtils.keep2Decimal(calculateNum());
        int len = totalMoney.length();
        SpannableString spannableString = new SpannableString(ResHelper.getString(R.string.down_order_sum,
                String.valueOf(mExtractBeanList.size()),totalMoney));
        int totalLength = spannableString.length();
        spannableString.setSpan(new SpannableMoney(this),
                totalLength-len-1,totalLength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tvProductSum.setText(spannableString);
    }

    private double calculateNum(){
        double sum = 0;
        for (int i=0;i<mExtractBeanList.size();i++){
            ProductExtractBean bean = mExtractBeanList.get(i);
            sum += bean.getPrice() * bean.getSelectSize();
        }
        totalMoney = sum;
        return sum;
    }

    /**
     * 回调数量....
     */
    @Override
    public void justCalculateTotalPrice() {
        setSumText();
    }
}
